package com.itheima.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.entity.Category;
import com.itheima.result.R;
import com.itheima.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/category")
public class CategoryController {
    @Autowired
    private CategoryService categoryService;

    @GetMapping("/page")
    public R<Page> SerachALL(Integer page, int pageSize) {
        LambdaQueryWrapper<Category> lqw = new LambdaQueryWrapper<>();
        LambdaQueryWrapper<Category> categoryLambdaQueryWrapper = lqw.orderByAsc(Category::getSort);
        Page<Category> pag = new Page<>(page, pageSize);
        Page<Category> page1 = categoryService.page(pag, categoryLambdaQueryWrapper);
        return R.success(page1);
    }

    @PostMapping
    public R<String> addCategory(@RequestBody Category category) {
        boolean save = categoryService.save(category);
        return save ? R.success("提交成功") : R.error("提交失败");
    }

    @PutMapping
    public R<String> updateCategory(@RequestBody Category category) {
        boolean save = categoryService.updateById(category);
        return save ? R.success("修改成功") : R.error("提交失败");
    }

    @DeleteMapping
    public R<String> deleteCategory(Long id) {
        categoryService.deleteByID(id);
        boolean b = categoryService.removeById(id);
        return b ? R.success("删除成功") : R.error("删除失败");
    }

    @GetMapping("/list")
    public R getCategor(Category category) {
        LambdaQueryWrapper<Category> queryWrapper = new LambdaQueryWrapper<>();
        //添加条件
        queryWrapper.eq(category.getType() != null, Category::getType, category.getType());
        //添加排序条件
        queryWrapper.orderByAsc(Category::getSort).orderByDesc(Category::getUpdateTime);

        List<Category> list = categoryService.list(queryWrapper);
        return R.success(list);
    }
}
